import axios from "axios";
import { ElMessage } from "element-plus";
import {publicMessage, useUser} from '@/store/index'
const baseAddress = '172.16.5.33:3000';
// const baseAddress = 'localhost:3000'
const url = 'http://'+baseAddress;
//封装api
const apiClient = axios.create({
    baseURL: url,
    headers: {
        "Content-Type": 'application/json'
    }
});


//默认头像
const defaultAvatar = "https://ts4.cn.mm.bing.net/th?id=OIP-C.DjCNDz2qUkQj4z0B-LhIsAAAAA&w=176&h=176&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2";
const header = {
    'Authorization':'hmz ' + localStorage.getItem('token')
};
export default {
    url,
    defaultAvatar,
    header,
    //用户注册
    register(data) {
        return apiClient.post(`/register`, data).then(resp => {
            ElMessage({
                message: resp.data.message
            })
            return resp.data.message
            // if(resp.data.message == "注册成功！") this.$router.push('/login') ;
        })
    },
    //登录
    login(data) {
        return apiClient.post(`/login`, data).then(resp => {
            ElMessage({
                message: resp.data.message
            })
            return resp.data;
        }).catch(error => {
            ElMessage.error('登陆失败，请检查用户名和密码！')
            console.log(error);
        })
    },
    //获得用户信息
    getUserInfo(){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
       return apiClient.get('/getUserInfo',{params:{token:'hmz ' + localStorage.getItem('token')}}).then( resp =>{
            return resp.data;
        })
    },
    //发布公告
    sendNotice(data) {
        const nowUser = useUser();
        data.personName = nowUser.userName;
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.post('/sendnotice', data).then(resp => {
            ElMessage.success(resp.data.message)
        });
    },
    //获取最新的三条公告
    getNotioce() {
        var pageSetting = {
            pageNow: 1,
            pageSize: 3
        }
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getnotice', { params: pageSetting }).then(resp => {
            return resp.data;
        })
    },
    //搜索用户
    getUserList(data) {
        const nowUser = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getuser', { params: { userName: data, self: nowUser.userId } }).then(resp => {
            return resp.data.list;
        })
    },
    //发送好友申请
    friendRequest(friendId){
        const nowUser = useUser();
        var data = {
            friendId: friendId,
            userId: nowUser.userId
        }
        //console.log(data);
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.post('/friendRequest', data).then(resp => {
            //console.log(resp.data.message);
            ElMessage.success(resp.data.message);
        })
    },
    //获取所有的好友申请
    getFriendRequest(){
        const userStore = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getFriendRequest', {params:{userId:userStore.userId}}).then(resp => {
            userStore.friendRequestList = resp.data.list
            ElMessage.success(resp.data.message);
        })
    },
    //添加好友
    addFriend(friendId) {
        const nowUser = useUser();
        var data = {
            friendId: friendId,
            userId: nowUser.userId
        }
        //console.log(data);
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.post('/addfriend', data).then(resp => {
            //console.log(resp.data.message);
            ElMessage.success(resp.data.message);
            location.reload();
        })
    },
    //获得好友列表
    getFriend() {
        const nowUser = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getfriend', { params: { userId: nowUser.userId } }).then(resp => {
            return resp.data;
        })
    },
    //获取消息列表
    getPrivateMessage(chatRoomId){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getPrivateMessage',{params:{chatRoomId:chatRoomId}}).then( resp=>{
            const  userStore =  useUser();
            userStore.pages = resp.data.total_pages;
            return resp.data.list;
        })
    },
    //获取更早的消息列表
    getOldMessage(chatRoomId,pageNow){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getOldMessage',{params:{chatRoomId:chatRoomId,pageNow:pageNow}}).then(resp=>{
            return resp.data.list;
        })
    },
    //创建webscoket 建立与服务端的链接
    createWebsocket(){
        const userStore = useUser();
        var websocket = new WebSocket(
            "ws://"+baseAddress+"/chat/" + localStorage.getItem("token")+'/'+userStore.chatId
          );
          websocket.onopen = function () {
            console.log("websocket已连接");
          };
          websocket.onerror = function () {
            console.log("websocket连接出现问题");
          };
          websocket.onclose = function () {
            console.log("websocket链接已关闭");
          };
          websocket.onmessage = function(resp){
            userStore.messageList.push(resp.data);
            userStore.isScrollBottom = !userStore.isScrollBottom;
            console.log('收到信息');
            
          }
        //   websocket.
          //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
          window.onbeforeunload = function () {
            websocket.close();
          };
          //监听窗口刷新事件，当窗口刷新时，主动去关闭websocket链接
          window.onbeforeunload = function () {
            // 在窗口即将关闭时执行的操作
            websocket.close(); // 关闭WebSocket连接
          };
          return websocket
    },
    //创建聊天室
    createChatRoom(chatRoomName){
        const nowUser = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.post('/createChatRoom',{chatRoomName:chatRoomName,userId:nowUser.userId}).then( resp=>{
            ElMessage.success(resp.data.message);
            location.reload();
        })
    },
    //搜索聊天室
    searchChatRoom(chatRoomName){
        const nowUser = useUser();
        const publicMessageStore = publicMessage();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/searchChatRoom', { params:{chatRoomName:chatRoomName,userId:nowUser.userId}}).then(resp =>{
            ElMessage.success(resp.data.message)
            publicMessageStore.chatRoomList = resp.data.list;
            console.log(resp.data);
        })
    },
    //获取我的所有聊天室
    getMyChatRoomList(){
        // console.log("getMyChatRoomList")
        const nowUser = useUser();
        const publicMessageStore = publicMessage();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        //console.log(nowUser.userId)
        return apiClient.get('/getMyChatRoomList',{params:{userId:nowUser.userId}}).then(resp=>{
            publicMessageStore.myChatRoomList = resp.data.list;
            //console.log(publicMessageStore.myChatRoomList)
            //console.log(publicMessageStore.myChatRoomList);
            ElMessage.success(resp.data.message)
        })
    },
    //加入聊天室
    joinChatRoom(chatRoomId){
        const nowUser = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        apiClient.post('/joinChatRoom',{chatRoomId:chatRoomId,userId:nowUser.userId}).then(resp=>{
            console.log(resp);
        })
    },
    //获得聊天室下所有的用户
    getChatRoomUserList(chatRoomId){
        const userStore = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getChatRoomUserList',{params:{chatRoomId:chatRoomId}}).then(resp=>{
            console.log(resp.data.message);
            userStore.userList = resp.data.list;
        })
    },
    //删除好友
    deleteFriend(friendId){
        const userStore  = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.post('/deleteFriend',{userId:userStore.userId,friendId:friendId}).then(resp=>{
            ElMessage.success(resp.data.message);
            location.reload();
        }
        )
    },
    //删除我的聊天室
    deleteMychatRoom(chatRoomId){
        const userStore = useUser();
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.post('/deleteMyChatRoom',{chatRoomId:chatRoomId,userId:userStore.userId}).then(resp=>{
            ElMessage.success(resp.data.message);
            location.reload();
        })
    },
    //获取指定聊天室下的指定人的所有发言
    getUserMessageListInChatRoom(chatRoomId,userId){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getUserMessageListInChatRoom',{params:{
            chatRoomId:chatRoomId,
            userId:userId
        }}).then(resp=>{
           return  resp.data.list
        })
    },
    //获取指定聊天室下的日期列表
    getTimeListInChatRoom(chatRoomId){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getTimeListInChatRoom',{params:{chatRoomId:chatRoomId}}).then(resp=>{
            return resp.data.list;
        })
    },
    //获取指定聊天室下指定日期的聊天记录
    getTimeMessageListInChatRoom(chatRoomId,date){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getTimeMessageListInChatRoom',{params:{chatRoomId,date:date}}).then(resp=>{
            return resp.data.list;
        })
    },
    //获取指定聊天室下指定类型的聊天记录
    getTypeMessageListInChatRoom(chatRoomId,type){
        apiClient.defaults.headers.common['Authorization'] = 'hmz ' + localStorage.getItem('token');
        return apiClient.get('/getTypeMessageListInChatRoom',{params:{chatRoomId:chatRoomId,type:type}}).then(resp =>{
            return resp.data.list;
        })
    },

}
